<?php

declare(strict_types=1);

namespace App\Controller\AdminApi;

use App\Exception\XZXValidationException;
use App\Middleware\AdminApi\AdminJWTAuthMiddleware;
use App\Service\MchAccountService;
use App\Service\SysExportLogService;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

/**
 * Class MchAccountController
 * @package App\Controller
 * @Controller(prefix="/admin/api/mchAccount")
 */
class MchAccountController extends AdminBaseController
{
    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var MchAccountService
     */
    protected $MchAccountService;

    /**
     * @Inject()
     * @var SysExportLogService
     */
    protected $SysExportLogService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required|uuid',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] =  $ext['isSuperRole'];
        if(!$param['isSuperRole']){
            $param['mchIdList'] =  $ext['mchIdList'];
        }
        $param['source'] = 2;
        return $this->MchAccountService->get($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(AdminJWTAuthMiddleware::class)
     */
    public function list(RequestInterface $request)
    {

        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'page' => 'required|integer|min:1',
                'limit' => 'required|integer|min:1',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }
        
        $param = $request->all();
        $ext = $this->request->getAttribute("ext");
        $param['isSuperRole'] =  $ext['isSuperRole'];
        if(!$param['isSuperRole']){
            $param['mchIdList'] =  $ext['mchIdList'];
        }

        $param['source'] = 2;

        if(isset($param['search'])){
            $search = $param['search'];
            CustomUtils::xzxAddSearch($param, $search, 'mchName');
            CustomUtils::xzxAddSearch($param, $search, 'mchNo');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
        }

        return $this->MchAccountService->list($param);
    }

    /**
     * 导出
     * @PostMapping(path = "exportExcel")
     * @Middleware(AdminJWTAuthMiddleware::class)
     * @param RequestInterface $request
     * @return array|mixed
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \Throwable
     * @throws \TypeError
     */
    public function exportExcel(RequestInterface $request) {

        $type = 2;

        // 新增导出记录
        $ext = $this->request->getAttribute("ext");
        $result = $this->SysExportLogService->add(['type' => $type, 'createBy'=>$ext['createBy']]);

        $param = $request->all();
        // 直接把页数拖到很大
        $param['page'] = $request->post('page', 1);
        $param['limit'] = 10000000;

        if(isset($param['search'])){
            $search = $param['search'];
            CustomUtils::xzxAddSearch($param, $search, 'mchName');
            CustomUtils::xzxAddSearch($param, $search, 'mchNo');
            CustomUtils::xzxAddSearch($param, $search, 'createTimeRange');
        }

        $logId = $result['data'];
        $fileName = 'account-' . date('YmdHis') . rand(1000, 9999);
        $xlsCell = [
            ['filed' => 'mchNo',                            'name'  => '商户号'],
            ['filed' => 'mchName',                          'name'  => '商户名称'],
            ['filed' => 'settleCurrency',                   'name'  => '结算币种'],
            ['filed' => 'floatTotalAccountCashAmount',      'name'  => '可用账户总金额'],
            ['filed' => 'floatTotalAccountFrozenAmount',    'name'  => '冻结账户总金额'],
            ['filed' => 'floatTradeFrozenAmount',           'name'  => '交易订单冻结金额'],
            ['filed' => 'floatBondFrozenAmount',            'name'  => '保证金冻结金额'],
            ['filed' => 'floatEventReviewFrozenAmount',     'name'  => '事件待审核冻结金额'],
            ['filed' => 'floatEventFrozenAmount',           'name'  => '事件冻结金额'],
        ];

        $this->SysExportLogService->addToTask([
            'logId'     => $logId,
            'fileName'  => $fileName,
            'type'      => $type,
            'param'     => $param,
            'xlsCell'   => $xlsCell
        ]);

        return $result;
    }
   
}